/**
 * 
 */
package vn.lumi.smarthome.ui;

/**
 * @author HuyHieu
 *
 */

import java.util.ArrayList;

import vn.lumi.smarthome.LumiHome;
import vn.lumi.smarthome.R;
import vn.lumi.smarthome.io.database.TBL_Scene;
import vn.lumi.smarthome.io.model.Scene;
import vn.lumi.smarthome.io.model.Scene.OnControlSceneListener;

import vn.lumi.smarthome.ulti.LogUltis;
import android.app.AlertDialog;
import android.app.ProgressDialog;
import android.content.BroadcastReceiver;
import android.content.ContentValues;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.IntentFilter;
import android.database.Cursor;
import android.graphics.Typeface;
import android.graphics.drawable.Drawable;
import android.os.Bundle;
import android.support.v4.app.FragmentActivity;
import android.support.v4.app.LoaderManager.LoaderCallbacks;
import android.support.v4.content.CursorLoader;
import android.support.v4.content.Loader;
import android.support.v4.widget.CursorAdapter;
import android.util.Log;
import android.view.ContextThemeWrapper;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.ListView;
import android.widget.TextView;
import android.widget.Toast;

public class EditSceneFragment extends BaseFragment implements
		LoaderCallbacks<Cursor> {
	private static final String TAG = "SceneFragment";

	private ListView mListScenes;
	private SceneEditAdapter mSceneEditAdapter;

	private static EditSceneFragment editSceneFragment;
	// Khai bao ID cua Loader
	private static final int LOADER_ID = 1;

	

	public EditSceneFragment() {
		LogUltis.i(TAG, "create EditSceneFragment");
	}

	public static EditSceneFragment newInstance(int floor_id, int room_id) {
		if (editSceneFragment == null) {
			editSceneFragment = new EditSceneFragment();
		}
		Bundle bundle = new Bundle();
		bundle.putInt(FLOOR_ID, floor_id);
		bundle.putInt(ROOM_ID, room_id);
		editSceneFragment.setArguments(bundle);
		return editSceneFragment;
	}

	@Override
	public void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		mFloor_id = getArguments().getInt(FLOOR_ID);
		mRoom_id = getArguments().getInt(ROOM_ID);
	}

	@Override
	public View onCreateView(LayoutInflater inflater, ViewGroup container,
			Bundle savedInstanceState) {
		// Dung chung voi scene
		View view = inflater.inflate(R.layout.fragment_scene, container, false);
		init_view(view);

		return view;
	}

	private void init_view(View view) {
		// Dung chung voi scene
		mListScenes = (ListView) view
				.findViewById(R.id.fragment_scene_list_scene);
		mSceneEditAdapter = new SceneEditAdapter(getActivity(), null,
				CursorAdapter.FLAG_REGISTER_CONTENT_OBSERVER);
		mSceneEditAdapter.initData(mFloor_id, mRoom_id);

		mListScenes.setAdapter(mSceneEditAdapter);
	}

	@Override
	public void onResume() {
		super.onResume();
		// load data
		refreshData(mFloor_id, mRoom_id);
	}

	@Override
	public void refreshData(int floor_id, int room_id) {
		mFloor_id = floor_id;
		mRoom_id = room_id;
		Bundle bundle = new Bundle();
		bundle.putInt(FLOOR_ID, mFloor_id);
		bundle.putInt(ROOM_ID, mRoom_id);
		getLoaderManager().restartLoader(LOADER_ID, bundle, this);
		mSceneEditAdapter.refreshData(floor_id, room_id);
	}

	@Override
	public Loader<Cursor> onCreateLoader(int id, Bundle bundle) {
		int room_id = bundle.getInt(ROOM_ID);
		String selection = TBL_Scene.ROOM_ID + "=?";
		String[] selectionArgs = new String[] { room_id + "" };
		return new CursorLoader(getActivity(), TBL_Scene.CONTENT_URI_SCENE,
				null, selection, selectionArgs, null);
	}

	@Override
	public void onLoadFinished(Loader<Cursor> arg0, Cursor arg1) {
		mSceneEditAdapter.swapCursor(arg1);
	}

	@Override
	public void onLoaderReset(Loader<Cursor> arg0) {
		mSceneEditAdapter.swapCursor(null);
	}

	private static class SceneEditAdapter extends CursorAdapter {
		int floor_id = 0;
		int room_id = 0;
		Context context;
		private static final String TAG = "SceneAdapter";
		public  BroadcastReceiver mDelSceneReceiver;

		public SceneEditAdapter(Context context, Cursor c, int flags) {
			super(context, c, flags);
			this.context = context;
		}

		public void initData(int floorID, int roomID) {
			floor_id = floorID;
			room_id = roomID;
		}

		public void refreshData(int floorID, int roomID) {
			floor_id = floorID;
			room_id = roomID;
		}

		@Override
		public void bindView(View view, final Context context, Cursor cursor) {
			final TextView txtName = (TextView) view
					.findViewById(R.id.item_listview_scene_edit_txt_name);
			ImageView imv_delete = (ImageView) view
					.findViewById(R.id.item_listview_scene_edit_delete);

			// set name
			final String sceneName = cursor.getString(cursor
					.getColumnIndex(TBL_Scene.NAME));
			txtName.setText(sceneName);

			// set state image
			final int state = cursor.getInt(cursor
					.getColumnIndex(TBL_Scene.STATE));
			if (state == Scene.SCENE_STATE_OFF) {

				txtName.setBackgroundResource(R.drawable.img_bg_dev_normal_name_off);
			} else if (state == Scene.SCENE_STATE_ON) {

				txtName.setBackgroundResource(R.drawable.img_bg_dev_normal_name_on);
			}

			// state image onclick
			final int sceneID = cursor.getInt(cursor
					.getColumnIndex(TBL_Scene._ID));
			

			imv_delete.setOnClickListener(new OnClickListener() {

				@Override
				public void onClick(View arg0) {
					// TODO Auto-generated method stub
					ArrayList<Integer> selectedScenes = new ArrayList<Integer>();
					selectedScenes.add(sceneID);
					// del scenes
					ContentValues values = new ContentValues();
					values.put(
							"Scene IDs",
							EditSceneFragment
									.convertIntArrayToString(convertArrayListToArray(selectedScenes)));
					context.getContentResolver().update(
							TBL_Scene.CONTENT_URI_DELETE_SCENE, values, null,
							null);

					// show dialog
					ProgressDialog dialog = new ProgressDialog(
							new ContextThemeWrapper(context,
									R.style.AlertDialogCustom));
					dialog.setMessage(context
							.getString(R.string.txt_saving_scene_in_HC));
					dialog.setCancelable(false);
					dialog.show();
					// Thay doi font chu cua Dialog
					ChangeFont changeFont = new ChangeFont(context);
					TextView textView = (TextView) dialog
							.findViewById(android.R.id.message);
					textView = changeFont.changeFontTextView(textView,
							R.string.txt_saving_scene_in_HC, LumiHome.font, 16,
							Gravity.NO_GRAVITY, context.getResources()
									.getColor(R.color.greenActionbar));

					// set broadcast receiver
					mDelSceneReceiver = new DelSceneReceiver(dialog);
					IntentFilter filter = new IntentFilter();
					filter.addAction(context.getString(R.string.txt_vn_lumi_smarthome_del_scenes_successful));
					filter.addAction(context.getString(R.string.txt_vn_lumi_smarthome_del_scenes_failed));
					context.registerReceiver(mDelSceneReceiver, filter);
				}

			});
			//set schedule
			final int mode = cursor.getInt(cursor.getColumnIndex(TBL_Scene.MODE));
			final int hour = cursor.getInt(cursor.getColumnIndex(TBL_Scene.HOUR));
			final int minute = cursor.getInt(cursor.getColumnIndex(TBL_Scene.MINUTE));
			
			//config onclick --> edit scene activity
			txtName.setOnClickListener(new OnClickListener(){

				@Override
				public void onClick(View arg0) {
					// TODO Auto-generated method stub
					Intent intent=new Intent(context, EditSceneActivity.class);
					intent.putExtra(EditSceneActivity.EXTRA_FLOOR_ID, floor_id);
					intent.putExtra(EditSceneActivity.EXTRA_ROOM_ID, room_id);
					intent.putExtra(EditSceneActivity.EXTRA_SCENE_ID, sceneID);
					intent.putExtra(EditSceneActivity.EXTRA_SCENE_NAME, sceneName);
					intent.putExtra(EditSceneActivity.EXTRA_SCENE_MODE, mode);
					intent.putExtra(EditSceneActivity.EXTRA_SCENE_HOUR, hour);
					intent.putExtra(EditSceneActivity.EXTRA_SCENE_MINUTE, minute);
					
					Log.d("SceneFragment","edit scene floorID="+floor_id+" room_id="+room_id+" sceneID="+sceneID+" sceneName="+sceneName +" mode="+mode+" "+hour+":"+minute);
					((FragmentActivity) context).startActivityForResult(intent, MainActivity.EDIT_SCENE_REQUEST);
				}
				
			});

		}

		@Override
		public View newView(Context context, Cursor cursor, ViewGroup viewgroup) {
			return View.inflate(context, R.layout.item_listview_scene_edit,
					null);
		}

		@Override
		public boolean isEnabled(int position) {
			// TODO Auto-generated method stub
			return false;
		}
		public class DelSceneReceiver extends BroadcastReceiver {

			private ProgressDialog mDialog;

			public DelSceneReceiver(ProgressDialog dialog) {
				mDialog = dialog;
			}

			@Override
			public void onReceive(Context context, Intent intent) {
				mDialog.cancel();
				context.unregisterReceiver(mDelSceneReceiver);
				if (intent
						.getAction()
						.equals(context
								.getString(R.string.txt_vn_lumi_smarthome_del_scenes_successful))) {

				} else if (intent
						.getAction()
						.equals(context
								.getString(R.string.txt_vn_lumi_smarthome_del_scenes_failed))) {
					showCustomDialog(R.string.txt_error,
							R.string.txt_error_cannot_connect_HC);
				}
			}

		}
		public void showCustomDialog(int title, int message) {
			AlertDialog.Builder ErrorDialog = new AlertDialog.Builder(
					new ContextThemeWrapper(context,
							R.style.AlertDialogCustom));

			ChangeFont changeFont = new ChangeFont(context);
			TextView tvTitle = new TextView(context);
			tvTitle = changeFont.changeFontTextView(tvTitle, title,
					LumiHome.fontBold, LumiHome.sizeTittle, Gravity.CENTER,
					context.getResources().getColor(R.color.green));
			ErrorDialog.setCustomTitle(tvTitle);
			ErrorDialog.setMessage(message);
			ErrorDialog.setNegativeButton(R.string.glb_txt_return,
					new DialogInterface.OnClickListener() {

						@Override
						public void onClick(DialogInterface dialog, int which) {
							dialog.cancel();
						}
					});
			AlertDialog alertErrorDialog = ErrorDialog.create();
			alertErrorDialog.show();
			alertErrorDialog.getWindow().getAttributes();
			TextView tvMessage = (TextView) alertErrorDialog
					.findViewById(android.R.id.message);
			tvMessage = changeFont.changeFontTextView(tvMessage, message,
					LumiHome.font, LumiHome.sizeContent, Gravity.NO_GRAVITY,
					context.getResources().getColor(R.color.greenLight));

			Button btn1 = alertErrorDialog
					.getButton(DialogInterface.BUTTON_NEGATIVE);
			btn1.setTypeface(Typeface.createFromAsset(context.getAssets(),
					LumiHome.fontBold));
			btn1.setTextColor(context.getResources().getColor(R.color.greenActionbar));
			btn1.setTextSize(LumiHome.sizeButton);
		}

	}

	public static String convertIntArrayToString(int[] data) {
		String result = "";
		for (int i = 0; i < data.length; i++) {
			result += String.valueOf(data[i]) + ",";
		}
		return result;

	}

	public static int[] convertStringToIntArray(String str) {
		if (str == "")
			return null;
		String[] array = str.split(",");
		int[] result = new int[array.length];
		for (int i = 0; i < array.length; i++) {
			result[i] = Integer.parseInt(array[i]);
		}
		return result;
	}

	public static int[] convertArrayListToArray(ArrayList<Integer> input) {
		int[] result = new int[input.size()];
		for (int i = 0; i < input.size(); i++) {
			result[i] = input.get(i);
		}
		return result;
	}
		
}
